package ua.vn.ticket_scanner.network.task.socket;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import ua.vn.ticket_scanner.network.data.ConnectResult;
import ua.vn.ticket_scanner.network.task.SuperBaseTask;
import ua.vn.ticket_scanner.network.task.socket.data.SocketInfo;

/**
 * Created by Ivan on 19.06.13.
 */
public abstract class BaseTask extends SuperBaseTask {

    private static final String TAG = "BaseTask";

    private String timeId = null;
    private SocketInfo socketInfo = null;

    public BaseTask(SocketInfo socketInfo) {
        this.socketInfo = socketInfo;
    }

    @Override
    protected ConnectResult doInBackground(Void... voids) {
        Log.i(TAG, "Socket: task started");
        makeJSON();
        Socket socket = openSocket(socketInfo);
        if (socket == null) {
            Log.e(TAG, "Socket: connection problems!");
            return null;
        }
        sendData(socket);
        ConnectResult result = readData(socket);
        Log.i(TAG, "Socket: task finished");
        return result;
    }

    private Socket openSocket(SocketInfo socketInfo) {
        Socket socket = null;
        try {
            socket = new Socket(socketInfo.getIp(), socketInfo.getPort());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (socket != null && socket.isConnected()) {
            return socket;
        }
        return null;
    }

    private void sendData(Socket socket) {
        try {
            BufferedWriter outStream = new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream()));

            String sendJson = getJSON().toString();
            Log.i(TAG, "Socket: JSON=" + sendJson);

            outStream.write(sendJson);
            outStream.write("/0");
            outStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ConnectResult readData(Socket socket) {
        ConnectResult connectResult = null;

        String inputLine = null;
        String result = "";
        BufferedReader in = null;

        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                result += result.concat(inputLine);
                if (inputLine.contains("/0"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.i(TAG, "Socket: result = " + result);

        if (result != null) {
            try {
                connectResult = parseJSON(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return connectResult;
    }

    private ConnectResult parseJSON(String result) throws JSONException {
        ConnectResult connectResult = new ConnectResult();
        JSONObject jsonResult = new JSONObject(result);
        connectResult.setJSON(jsonResult);
        return connectResult;
    }


}
